import { Injectable } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { Finance } from './finance.schema'
import { json } from 'stream/consumers';
import { platform } from 'os';
//引入ws模块 
const webSocket = require('ws').Server;
const port = 3001;
// 创建一个服务
const server = new webSocket({ port }, () => {
  console.log('server is running on port 3001');
})

const connectHandler = (ws) => {
  //监听客户端连接
  console.log('client connected');
  //监听客户端出错
  ws.on('error', errHandler)
  //监听客户端关闭
  ws.on('close', closeHandler)
  //监听客户端发送消息
  ws.on('message', messageHandler)
}

const errHandler = (err) => {
  console.log('client error', err);
}
const closeHandler = (e) => {
  console.log('client close', e.data);
}
function messageHandler(data) {
  console.log('client message', data);
  const { ModeCode } = JSON.parse(data)
  switch (ModeCode) {
    case "message":
      console.log('收到普通消息')
      break;
    case "heart_beat":
      console.log('收到心跳消息')
      this.send(JSON.stringify(JSON.parse(data)))
      break;
  }
}

//建立连接
server.on('connection', connectHandler)

@Injectable()
export class FinanceService {
  constructor(@InjectModel(Finance.name) private finance: Model<Finance>) { }
  async getFinanceDate(req, res) {
    let data = await this.finance.find()
     const data1 = await this.finance.aggregate([
       {
         $group: {
           _id: '$platform',
           order: { $sum: '$order' },
           unSettled: { $sum: '$unSettled' },
           settled: { $sum: '$settled' },
           returnOrder: { $sum: '$returnOrder' },
           children: { $push: '$children' },
         },
       },
       {
         $unwind: '$children', // 展开children字段
       },
       {
         $unwind: '$children', // 展开children字段
       },
       {
         $group: {
           _id: { platform: '$_id', children: '$children.platform' },
           order: { $sum: '$order' },
           unSettled: { $sum: '$unSettled' },
           settled: { $sum: '$settled' },
           returnOrder: { $sum: '$returnOrder' },
         },
       },
       {
         $group: {
           _id: '$_id.platform',
           order: { $sum: '$order' },
           unSettled: { $sum: '$unSettled' },
           settled: { $sum: '$settled' },
           returnOrder: { $sum: '$returnOrder' },
           children: {
             $push: {
               platform: '$_id.children',
               order: '$order',
               unSettled: '$unSettled',
               settled: '$settled',
               returnOrder: '$returnOrder',
             },
           },
         },
       },
     ])
     let platformArr = []
     const orderArr = []
     const unSettledArr = []
     const settledArr = []
     const returnOrderArr = []
     data.forEach((item: any) => {
       if (!platformArr.includes(item.platform)) {
         if (item.children) {
           item.children.forEach((item: any) => {
             if (!platformArr.includes(item.platform))
               platformArr.push(item.platform)
           })
         }
         platformArr.push(item.platform)
       }
     })
     // 获取订单总量  未结算订单 已结算订单 退订订单
     data1.forEach((item: any) => {
       if (item.children) {
         item.children.forEach((item: any) => {
           orderArr.push(item.order)
           unSettledArr.push(item.unSettled)
           settledArr.push(item.settled)
           returnOrderArr.push(item.returnOrder)
         })
       }
       orderArr.push(item.order)
       unSettledArr.push(item.unSettled)
       settledArr.push(item.settled)
       returnOrderArr.push(item.returnOrder)
     })
     const FinanceTrend = {
       xAxis: {
         data: platformArr,
       },
       legend: {
         data: ['订单总量', '未结算订单', '已结算订单', '退订订单'],
         show: true,
       },
       series: [
         {
           name: '订单总量',
           type: 'bar',
           data: orderArr,
           stack: 'x',
         },
         {
           name: '未结算订单',
           type: 'bar',
           data: unSettledArr,
           stack: 'x',
         },
         {
           name: '已结算订单',
           type: 'bar',
           data: settledArr,
           stack: 'x',
         },
         {
           name: '退订订单',
           type: 'bar',
           data: returnOrderArr,
           stack: 'x',
         },
       ],
       // 标记
     }
    res.send({
      code: 200,
      data: data,
      FinanceTrend: FinanceTrend,
    })
  }


  formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  }
  getDateRange(days) {
    const today = new Date();
    const dates = [];
  
    for (let i = 0; i < days; i++) {
      const date = new Date(today);
      date.setDate(today.getDate() - i);
      dates.push(this.formatDate(date));
    }
  
    return dates.reverse(); // 如果你希望日期从最早到最新排列，可以调用 reverse()
  }
  async searchFinanceData(req, res) {
    const { brand, partition, shop, platform, date,today } = req.body
    const days = this.getDateRange(today)
    const arr = [{}]
    if (brand) {
      arr.push({ brand: brand })
    }
    if (partition) {
      arr.push({ partition: partition })
    }
    if (shop) {
      arr.push({ shop: shop })
    }
    if (platform) {
      arr.push({ platform: platform})
    }
    if (date) {
      arr.push({ date: date })
    }
    if (days) {
      arr.push({ date: { $in: days } })
    }
    const data = await this.finance.find({ $and: arr })
    const data1 = await this.finance.aggregate([
      {
        $group:{
          _id: "$platform",
          order:{"$sum":"$order"},
          unSettled:{"$sum":"$unSettled"},
          settled:{"$sum":"$settled"},
          returnOrder:{"$sum":"$returnOrder"},
          children:{"$push":"$children"}
        }
      },
      {
        $unwind: "$children",// 展开children字段
      },
      {
        $unwind: "$children",// 展开children字段
      },
      {
        $group:{
          _id:{platform:"$_id",children:"$children.platform"},
          order:{"$sum":"$order"},
          unSettled:{"$sum":"$unSettled"},
          settled:{"$sum":"$settled"},
          returnOrder:{"$sum":"$returnOrder"},
        }
      },
      {
        $group:{
          _id:"$_id.platform",
          order:{"$sum":"$order"},
          unSettled:{"$sum":"$unSettled"},
          settled:{"$sum":"$settled"},
          returnOrder:{"$sum":"$returnOrder"},
          children:{"$push":{
            platform:"$_id.children",
            order:"$order",
            unSettled:"$unSettled",
            settled:"$settled",
            returnOrder:"$returnOrder",
          }}
        }
      }
    ])
    let platformArr = []
    const orderArr = []
    const unSettledArr = []
    const settledArr = []
    const returnOrderArr = []
    data.forEach((item: any) => {
      if (!platformArr.includes(item.platform)) {
        if (item.children) {
          item.children.forEach((item: any) => {
            if (!platformArr.includes(item.platform))
              platformArr.push(item.platform)
          })
        }
        platformArr.push(item.platform)
      }

    })
    // 获取订单总量  未结算订单 已结算订单 退订订单
    data1.forEach((item: any) => {
      if(item.children){
        item.children.forEach((item: any) => {
            orderArr.push(item.order)
            unSettledArr.push(item.unSettled)
            settledArr.push(item.settled)
            returnOrderArr.push(item.returnOrder)
        })       
      }
      orderArr.push(item.order)
      unSettledArr.push(item.unSettled)
      settledArr.push(item.settled)
      returnOrderArr.push(item.returnOrder)
    })
    const FinanceTrend = {
      xAxis: {
        data: platformArr
      },
      legend: {
        data: ['订单总量', '未结算订单', '已结算订单', '退订订单'],
        show: true,
      },
      series: [
        {
          name: '订单总量',
          type: 'bar',
          data: orderArr,
          stack: "x"
        },
        {
          name: '未结算订单',
          type: 'bar',
          data:  unSettledArr ,
          stack: "x"
        },
        {
          name: '已结算订单',
          type: 'bar',
          data: settledArr,
          stack: "x"
        },
        {
          name: '退订订单',
          type: 'bar',
          data: returnOrderArr,
          stack: "x"
        }
      ],
      // 标记
     
    }

    res.send({
      code: 200,
      data: data,
      FinanceTrend: FinanceTrend,
    })
  }
  async addFinanceData(body: any) {
    return await this.finance.create(body)
  }
}
